import React from 'react';
import { connect } from 'dva';
import { DownOutlined, UpOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {
  Card,
  Button,
  Input,
  Row,
  Col,
  Tabs,
  Spin,
  Divider,
  DatePicker,
  Progress,
  message,
} from 'antd';
import queryString from 'query-string';
import moment from 'moment';
import router from 'umi/router';
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import Authorized from '@/utils/Authorized';
import styles from '@/utils/utils.less';
import downloadFile from '@/utils/utils';
import DictCode from '../../components/DictCode';
import Area from '../../components/Area';

const FormItem = Form.Item;
const { TabPane } = Tabs;
const { RangePicker } = DatePicker;
@connect(({ replacetask, loading }) => ({
  loading: loading.models.replacetask,
  formFieldsValue: replacetask.formFieldsValue,
  expandForm: replacetask.expandForm,
  activeKey: replacetask.activeKey,
  pageData: replacetask.pageData,
  valuesArr: replacetask.valuesArr,
  tabList: replacetask.tabList,
}))
class BasicList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedRowKeys: [],
      selectedRows: [],
    };
    // 表单布局
    this.formItemLayout = {
      labelCol: { span: 7 },
      wrapperCol: { span: 16 },
    };
  }

  componentDidMount = () => {
    this.getInitialList();
  };

  getInitialList = () => {
    const {
      pageData: { pagination },
      dispatch,
      location,
      formFieldsValue,
      activeKey,
    } = this.props;
    const tempActiveKey = queryString.parse(location.search).activeKey || activeKey;
    if (location.queryParam) {
      dispatch({
        type: 'replacetask/updateModelData',
        payload: { formFieldsValue: location.queryParam, expandForm: true },
      });
    }
    dispatch({
      type: 'replacetask/updateModelData',
      payload: {
        activeKey: tempActiveKey,
      },
    });
    this.searchList(
      this.processFormData({ ...formFieldsValue }),
      tempActiveKey,
      pagination.current,
      pagination.pageSize
    );
  };

  // 点击查询按钮
  searchBtnList = activeKey => {
    const { form, valuesArr, dispatch } = this.props;
    form.validateFieldsAndScroll([...valuesArr], (err, values) => {
      if (!err) {
        dispatch({
          type: 'replacetask/updateModelData',
          payload: {
            formFieldsValue: values,
            activeKey,
          },
        });
        this.searchList(this.processFormData(values), activeKey);
      }
    });
  };

  // 查询
  searchList = (
    formFieldsValue,
    activeKey = '1',
    currentPage = 1,
    pageSize = 10,
    isClear = true
  ) => {
    if (isClear) {
      this.setState({ selectedRows: [], selectedRowKeys: [] });
    }
    const { dispatch } = this.props;
    const pageArg = { currentPage, pageSize };
    const values = {
      ...formFieldsValue,
      taskTab: activeKey,
      pageArg,
    };

    dispatch({
      type: 'replacetask/updateModelData',
      payload: {
        values,
      },
    });

    dispatch({
      type: 'replacetask/fetchList',
      payload: values,
    });
  };

  // 处理form数据
  processFormData = fieldsValue => {
    const formFieldsValue = {};
    const tempFieldsValue = fieldsValue;
    Object.keys(tempFieldsValue).forEach(key => {
      if (key === 'operTime') {
        formFieldsValue.startTime =
          (tempFieldsValue.operTime &&
            tempFieldsValue.operTime[0] &&
            tempFieldsValue.operTime[0].format('YYYY-MM-DD')) ||
          null;
        formFieldsValue.endTime =
          (tempFieldsValue.operTime &&
            tempFieldsValue.operTime[1] &&
            tempFieldsValue.operTime[1].format('YYYY-MM-DD')) ||
          null;
      }
      if (tempFieldsValue[key] && tempFieldsValue[key].key) {
        formFieldsValue[key] =
          tempFieldsValue[key].key === undefined ? null : tempFieldsValue[key].key;
      } else {
        formFieldsValue[key] = tempFieldsValue[key] === undefined ? null : tempFieldsValue[key];
      }
      delete formFieldsValue.operTime;
    });
    return formFieldsValue;
  };

  // 重置
  resetSearch = () => {
    const { form, dispatch } = this.props;
    dispatch({
      type: 'replacetask/updateModelData',
      payload: { formFieldsValue: {} },
    });
    form.resetFields();
    form.setFieldsValue({ operTime: null });
  };

  // 展开收起
  toggleForm = () => {
    const { dispatch, expandForm } = this.props;
    dispatch({
      type: 'replacetask/updateModelData',
      payload: { expandForm: !expandForm },
    });
  };

  // 切换页签
  changeTabPane = activeKey => {
    const { dispatch, location, formFieldsValue } = this.props;
    // 更改当前models里面state的数据
    router.push({
      pathname: location.pathname,
      query: {
        activeKey,
      },
    });
    dispatch({
      type: 'replacetask/updateModelData',
      payload: {
        activeKey,
        formFieldsValue: {
          ...formFieldsValue,
        },
      },
    });
    this.setState({ selectedRows: [], selectedRowKeys: [] }, () => {
      this.searchList(this.processFormData(formFieldsValue), activeKey);
    });
  };

  // 点击复选框
  handleSelectRows = (selectedRows, selectedRowKeys) => {
    this.setState({ selectedRows, selectedRowKeys });
  };

  // 表格有变化：比如：切换页码
  handleStandardTableChange = pagination => {
    const { activeKey, formFieldsValue } = this.props;
    this.searchList(
      this.processFormData(formFieldsValue),
      activeKey,
      pagination.current,
      pagination.pageSize,
      false
    );
  };

  // 生成替数明细，执行替数
  replaceDetail = (type) => {
    const { selectedRowKeys } = this.state;
    const {
      dispatch,
      formFieldsValue,
      activeKey,
      pageData: { pagination },
    } = this.props;
    if (selectedRowKeys.length) {
      dispatch({
        type: 'replacetask/creExcuteTask',
        payload: {
          params: {
            replTaskIds: selectedRowKeys,
          },
          type,
        },
      }).then(response => {
        if (response.success) {
          this.setState({ selectedRowKeys: [], selectedRows: [] }, () => {
            this.searchList(
              this.processFormData(formFieldsValue),
              activeKey,
              pagination.current,
              pagination.pageSize
            );
          });
        } else {
          message.warning(
            response.message || `${type === 1 ? `生成替数明细` : `执行替数`}：服务器端错误!`
          );
        }
      });
    } else {
      message.warning('请至少选择一条数据！');
    }
  };

  // 导出替数结果
  exportResult = () => {
    const { selectedRowKeys } = this.state;
    if (selectedRowKeys.length > 1) {
      message.warning('只能选择一条数据！');
    } else if (selectedRowKeys.length === 0) {
      message.warning('请至少选择一条数据！');
    } else {
      downloadFile({ replTaskId: selectedRowKeys[0] }, '/mgrApi/repl/export', 'POST');
    }
  };

  // 查看
  goDetail = record => {
    const { activeKey } = this.props;
    router.push(
      `/replacemanage/replacetask/detail?replTaskId=${record.replTaskId}&activeKey=${activeKey}`
    );
  };

  // 下载
  downLoad = record => {
    downloadFile({ replTaskId: record.replTaskId }, '/mgrApi/repl/download', 'POST');
  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
      formFieldsValue,
      activeKey,
    } = this.props;
    return (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem {...this.formItemLayout} label="替数任务类型">
              {getFieldDecorator('taskType', {
                initialValue: formFieldsValue.taskType,
              })(<DictCode dictType="REPL_TASK_TYPE" allowClear />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem {...this.formItemLayout} label="地区">
              {getFieldDecorator('areaId', {
                initialValue: formFieldsValue.areaId,
              })(<Area allowClear labelInValue />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" onClick={() => this.searchBtnList(activeKey)}>
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.resetSearch}>
                重置
              </Button>
              <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                展开 <DownOutlined />
              </a>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderAdvancedForm() {
    const {
      form: { getFieldDecorator },
      formFieldsValue,
      activeKey,
    } = this.props;
    return (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem {...this.formItemLayout} label="替数任务类型">
              {getFieldDecorator('taskType', {
                initialValue: formFieldsValue.taskType,
              })(<DictCode dictType="REPL_TASK_TYPE" allowClear />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem {...this.formItemLayout} label="地区">
              {getFieldDecorator('areaId', {
                initialValue: formFieldsValue.areaId,
              })(<Area allowClear labelInValue />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem {...this.formItemLayout} label="任务创建时间">
              {getFieldDecorator('operTime', {
                initialValue: formFieldsValue.operTime,
              })(
                <RangePicker
                  placeholder={['开始时间', '结束时间']}
                  style={{ width: '100%' }}
                  format="YYYY-MM-DD"
                />
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24} />
          <Col md={8} sm={24} />
          <Col md={8} sm={24}>
            <div style={{ overflow: 'hidden' }}>
              <span style={{ float: 'right', marginBottom: 24 }}>
                <Button type="primary" onClick={() => this.searchBtnList(activeKey)}>
                  查询
                </Button>
                <Button style={{ marginLeft: 8 }} onClick={this.resetSearch}>
                  重置
                </Button>
                <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                  收起 <UpOutlined />
                </a>
              </span>
            </div>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    const { expandForm } = this.props;
    return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
  }

  render() {
    const { tabList, activeKey, pageData, loading } = this.props;
    const { selectedRows, selectedRowKeys } = this.state;

    // 已创建的表格数据
    const createdColumns = [
      {
        title: '替数任务类型',
        dataIndex: 'taskTypeName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => (text && text) || '--',
      },
      {
        title: '地区',
        dataIndex: 'areaIdName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => (text && text) || '--',
      },
      {
        title: '关联请求数量',
        dataIndex: 'reqNum',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => (text && text) || '--',
      },
      {
        title: '生成明细进度',
        dataIndex: 'factorSchedule',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: (text, record) => <Progress percent={record.progress} size="small" />,
      },
      {
        title: '任务创建时间',
        dataIndex: 'creTime',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => (text ? moment(text).format('YYYY-MM-DD HH:mm') : '--'),
      },
      {
        title: '操作',
        dataIndex: 'operation',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', width: 150, textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        render: (text, record) => (
          <span>
            <a onClick={() => this.goDetail(record)}>查看</a>
          </span>
        ),
      },
    ];

    // 待执行的表格数据
    const executedColumns = [
      {
        title: '替数任务类型',
        dataIndex: 'taskTypeName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => (text && text) || '--',
      },
      {
        title: '地区',
        dataIndex: 'areaIdName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => (text && text) || '--',
      },
      {
        title: '关联请求数量',
        dataIndex: 'reqNum',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => (text && text) || '--',
      },
      {
        title: '替数涉及人数',
        dataIndex: 'empNum',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => (text && text) || '--',
      },
      {
        title: '任务创建时间',
        dataIndex: 'creTime',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => (text ? moment(text).format('YYYY-MM-DD HH:mm') : '--'),
      },
      {
        title: '操作',
        dataIndex: 'operation',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', width: 150, textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        render: (text, record) => (
          <span>
            <a onClick={() => this.goDetail(record)}>查看</a>
          </span>
        ),
      },
    ];

    // 执行中的表格数据
    const executingColumns = [
      {
        title: '替数任务类型',
        dataIndex: 'taskTypeName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: (text, record) => (
          <div>
            {Number(record.detErrNum) > 0 && (
              <span
                style={{
                  marginTop: '1px',
                  marginLeft: '-10px',
                  border: '1px solid red',
                  width: '64px',
                  color: 'red',
                  borderRadius: '4px',
                  fontSize: '16px',
                  WebkitTextSizeAdjust: 'none',
                  display: 'inline-block',
                  transform: 'scale(0.5)',
                  textAlign: 'center',
                }}
              >
                异常
              </span>
            )}
            {(text && text) || '--'}
          </div>
        ),
      },
      {
        title: '地区',
        dataIndex: 'areaIdName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => (text && text) || '--',
      },
      {
        title: '关联请求数量',
        dataIndex: 'reqNum',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => (text && text) || '--',
      },
      {
        title: '替数涉及人数',
        dataIndex: 'empNum',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => (text && text) || '--',
      },
      {
        title: '替数开始时间',
        dataIndex: 'execBeginTime',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => (text ? moment(text).format('YYYY-MM-DD HH:mm') : '--'),
      },
      {
        title: '预计时长',
        dataIndex: 'planTime',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => (text && text) || '--',
      },
      {
        title: '任务创建时间',
        dataIndex: 'creTime',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => (text ? moment(text).format('YYYY-MM-DD HH:mm') : '--'),
      },
      {
        title: '操作',
        dataIndex: 'operation',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', width: 150, textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        render: (text, record) => (
          <span>
            <a onClick={() => this.goDetail(record)}>查看</a>
            {Number(record.detErrNum) > 0 && <Divider type="vertical" />}
            {Number(record.detErrNum) > 0 && <a onClick={() => this.downLoad(record)}>下载</a>}
          </span>
        ),
      },
    ];

    // 已完成的表格数据
    const finishedColumns = [
      {
        title: '替数任务类型',
        dataIndex: 'taskTypeName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => (text && text) || '--',
      },
      {
        title: '地区',
        dataIndex: 'areaIdName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => (text && text) || '--',
      },
      {
        title: '关联请求数量',
        dataIndex: 'reqNum',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => (text && text) || '--',
      },
      {
        title: '替数涉及人数',
        dataIndex: 'empNum',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => (text && text) || '--',
      },
      {
        title: '替数开始时间',
        dataIndex: 'execBeginTime',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => (text ? moment(text).format('YYYY-MM-DD HH:mm') : '--'),
      },
      {
        title: '替数结束时间',
        dataIndex: 'execEndTime',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => (text ? moment(text).format('YYYY-MM-DD HH:mm') : '--'),
      },
      {
        title: '替数失败人数',
        dataIndex: 'detErrNum',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => (text && text) || '--',
      },
      {
        title: '任务创建时间',
        dataIndex: 'creTime',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => (text ? moment(text).format('YYYY-MM-DD HH:mm') : '--'),
      },
      {
        title: '操作',
        dataIndex: 'operation',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', width: 150, textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        render: (text, record) => (
          <span>
            <a onClick={() => this.goDetail(record)}>查看</a>
            {Number(record.detErrNum) > 0 && <Divider type="vertical" />}
            {Number(record.detErrNum) > 0 && <a onClick={() => this.downLoad(record)}>下载</a>}
          </span>
        ),
      },
    ];

    // 已创建
    const created = (
      <div>
        <Row style={{ marginBottom: '16px' }}>
          <Authorized authority="" noMatch={null}>
            <Button
              type="primary"
              style={{ marginRight: '8px' }}
              onClick={() => this.replaceDetail(1)}
            >
              生成替数明细
            </Button>
          </Authorized>
        </Row>
        <StandardTable
          selectedRows={selectedRows}
          selectedRowKeys={selectedRowKeys}
          loading={loading}
          data={pageData}
          rowKey="replTaskId"
          columns={createdColumns}
          onSelectRow={this.handleSelectRows}
          onChange={this.handleStandardTableChange}
        />
      </div>
    );

    // 待执行
    const executed = (
      <div>
        <Row style={{ marginBottom: '16px' }}>
          <Authorized authority="" noMatch={null}>
            <Button
              type="primary"
              style={{ marginRight: '8px' }}
              onClick={() => this.replaceDetail(2)}
            >
              执行替数
            </Button>
          </Authorized>
        </Row>
        <StandardTable
          selectedRows={selectedRows}
          selectedRowKeys={selectedRowKeys}
          loading={loading}
          data={pageData}
          rowKey="replTaskId"
          columns={executedColumns}
          onSelectRow={this.handleSelectRows}
          onChange={this.handleStandardTableChange}
        />
      </div>
    );

    // 执行中
    const executing = (
      <div>
        <StandardTable
          selectedRows={selectedRows}
          selectedRowKeys={selectedRowKeys}
          loading={loading}
          data={pageData}
          rowKey="replTaskId"
          columns={executingColumns}
          onSelectRow={this.handleSelectRows}
          onChange={this.handleStandardTableChange}
        />
      </div>
    );

    // 已完成
    const finished = (
      <div>
        <Row style={{ marginBottom: '16px' }}>
          <Authorized authority="" noMatch={null}>
            <Button type="primary" style={{ marginRight: '8px' }} onClick={this.exportResult}>
              导出替数结果
            </Button>
          </Authorized>
        </Row>
        <StandardTable
          selectedRows={selectedRows}
          selectedRowKeys={selectedRowKeys}
          loading={loading}
          data={pageData}
          rowKey="replTaskId"
          columns={finishedColumns}
          onSelectRow={this.handleSelectRows}
          onChange={this.handleStandardTableChange}
        />
      </div>
    );

    // 获取页签组件
    const getTabPane = activeKeys => {
      if (activeKeys === 1) {
        return created;
      }
      if (activeKeys === 2) {
        return executed;
      }
      if (activeKeys === 3) {
        return executing;
      }
      if (activeKeys === 4) {
        return finished;
      }
    };

    return (
      <PageHeaderWrapper>
        <Spin tip="Loading..." spinning={loading}>
          <Card className={styles.searchCard}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
          </Card>
          <Card className={styles.tabCard}>
            <div className={styles.tableList}>
              <Tabs activeKey={activeKey} onChange={this.changeTabPane}>
                {tabList.map((item, index) => (
                  // eslint-disable-next-line react/no-array-index-key
                  <TabPane tab={item.name} key={index + 1}>
                    {getTabPane(index + 1)}
                  </TabPane>
                ))}
              </Tabs>
            </div>
          </Card>
        </Spin>
      </PageHeaderWrapper>
    );
  }
}

const ListSearchForm = Form.create()(BasicList);
export default ListSearchForm;
